// pages/map/map.js
const app = getApp();
// import { networkList } from '../../static/js/network';
const loc = "/static/images/scrcu_green.png";
const atm = "/static/images/ATM_before.png";
const selected_atm = "/static/images/ATM_after.png";
const navi_loc = "/static/images/loc@.png";
const selected_loc = "/static/images/scrcu_blue.png";
const offline_loc = "/static/images/scrcu_off.png";
const search = "/static/images/search.png";
const nores = "/static/images/nores.png";
const search_city = "/static/images/loc_not.png";
var funcs = require('../../static/js/func.js');

import {
  cities,
  areas
} from '../../static/js/city';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fst_cnt:0,
    atm,
    selected_atm,
    display_flag: true,
    loc,
    offline_loc,
    navi_loc,
    selected_loc,
    objectMultiArray: [cities, areas[0]],
    multiIndex: [0, 0],
    cities,
    areas,
    city_name: "",
    area_name: "",
    search_city,
    nores,
    search,
    networkList: [],
    my_latitude: 0.0,
    my_longitude: 0.0,
    jigou_type: 1,
    shaixuan_toggle: 0,
    shaixuan_item: ['个人贷款', '社保', '公积金', '税务服务', '快递驿站', '存款办理'],
    shaixuan_select: [0, 0, 0, 0, 0, 0],
    icon_type: 0,
  },
  //判断是否在营业时间内
  judgeTime:function(){
    let now = new Date();
    // 获取当前时间的小时
    let hour = now.getHours();
    let mini = now.getMinutes();
    console.log("当前时间："+hour+":"+mini)
    if(9<=hour && hour < 18){
      if(hour==17 && mini>30){
        this.setData({
          open_flag: false,
          loc:offline_loc
        })
      }else{
        this.setData({
          open_flag: true,
          loc: loc
        })
      }
    }else{
        this.setData({
          open_flag: false,
          loc:offline_loc
        })
      }
  },

  jigou_type_event(event) {
    this.setData({
      jigou_type: this.data.jigou_type == 1 ? 0 : 1
    })
    this.reloadDataByCityName(this.data.city_name,this.data.area_name,false)
  },
  shaixuan_event(event) {
    this.setData({
      shaixuan_toggle: this.data.shaixuan_toggle == 1 ? 0 : 1
    })
  },
  shaixuan_type_event(event) {
    let index = event.currentTarget.dataset.index
    let shaixuan_select = this.data.shaixuan_select
    shaixuan_select[index] = shaixuan_select[index] == 1 ? 0 : 1;
    this.setData({
      shaixuan_select: shaixuan_select
    })
    console.log(shaixuan_select)
  },

  getDataFilterByName:function(cityname){
    return new Promise((resolve, reject) => {
        if(this.data.jigou_type==1){
          funcs.getInstDatabyName(cityname).then(res=>{
            // console.log(res)
            resolve(res);
          })
        }else if(this.data.jigou_type==0){
          funcs.getATMByCityName(cityname).then(res=>{
            resolve(res);
          })
        }
    });
  },
  //city选择
  bindCityChange(event) {
    this.judgeTime()
    console.log('picker发送选择改变，携带值为', event.detail.value)
    let city_index = event.detail.value[0];
    let area_index = event.detail.value[1];
    let city = this.data.cities[city_index].name;
    let area = this.data.objectMultiArray[1][area_index].name;
    this.setData({
        city_name:city,
        area_name:area
    })
    console.log(city + ":" + area)
    this.reloadDataByCityName(city,area,true)
  },
  //city切换
  bindColumnCityChange(event) {
    console.log('修改的列为', event.detail.column, '，值为', event.detail.value);
    switch (event.detail.column) {
      case 0: //修改第一列
        let arr = this.data.multiIndex;
        arr[0] = event.detail.value;
        arr[1] = 0;
        this.setData({
          objectMultiArray: [cities, areas[event.detail.value]],
          multiIndex: arr,
        })
        break;
      case 1: //修改第二列
        let arr2 = this.data.multiIndex;
        arr2[1] = event.detail.value;
        // console.log(arr2)
        this.setData({
          multiIndex: arr2,
        })
        break;
    }
  },

  //area选择
  bindAreaChange(event) {
    let index = event.detail.value;
    let area = this.data.cities[index].name;
    this.setData({
      area: area
    })
  },

  markerTap: function (option) {
    let id = option.detail.markerId
    console.log(option.detail.markerId)
    console.log(this.data.markers[id])
    let name = this.data.markers[id].name
    let latitude = this.data.markers[id].latitude
    let longitude = this.data.markers[id].longitude
    let address = this.data.markers[id].address
    let telephone = this.data.markers[id].telephone

    let mylatitude = app.globalData.latitude;
    let mylongitude = app.globalData.longitude;

    let distance = funcs.getDistance(latitude, longitude, mylatitude, mylongitude);
    console.log(name + latitude + ":" + longitude + "  " + address + ":" + telephone + ":" + distance)
    
    let tempmarkers = this.data.markers;
    let last_id = this.data.last_selected_id;

    //地图机构图标点击动态修改
    if (last_id != null) {
      tempmarkers[last_id].iconPath = this.data.jigou_type==1?this.data.loc:atm;
      tempmarkers[last_id].width = 25;
      tempmarkers[last_id].height = 25;
    }
    tempmarkers[id].iconPath = this.data.jigou_type==1?selected_loc:selected_atm;
    tempmarkers[id].width = 32;
    tempmarkers[id].height = 32;

    console.log("打印测试" + tempmarkers[id].telephone)
    this.setData({
      display_flag: true,
      last_selected_id: id,
      markers: tempmarkers,
      selected_name: name,
      selected_address: address,
      selected_latitude: latitude,
      selected_longitude: longitude,
      selected_telephone: telephone,
      selected_distance: distance
    })

  },
  jumptomap: function (res) {
    let data = res.currentTarget.dataset

    let longitude = data.longitude;
    let latitude = data.latitude;

    console.log(latitude + latitude + data.nam + data.address)
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: data.name,
      address: data.address
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("当前用户openid为>"+app.globalData.openid)

    wx.showLoading({
      title: '加载中'
    })
    this.judgeTime()
    let _this = this;
    let mylatitude = app.globalData.latitude;
    let mylongitude = app.globalData.longitude;
    funcs.getAddressByKey(mylatitude, mylongitude).then(res => {
      // console.log(res.data.result.ad_info.district)
      let areaname = res.data.result.ad_info.district
      let cityname = res.data.result.ad_info.city;
      _this.setData({
        city_name: cityname,
        area_name: areaname
      })
      _this.reloadDataByCityName(cityname,areaname,true)
    })
  },


  reloadDataByCityName: function (cityname, areaname, switchFlag) {
    console.log("reloadDataByCityName"+cityname + ":" + areaname)
    let _this = this;
    var tempMarkers = [];
    var targetMarkers = [];
    let mylatitude = app.globalData.latitude;
    let mylongitude = app.globalData.longitude;

    _this.getDataFilterByName(cityname).then(res => {
      // console.log(res.data);
      let networkList = res.data.data;
      // console.log(res.data)
      
      let id = 0;
      networkList.forEach((m, index) => {
        var info = {
          id: 0,
          iconPath: this.data.jigou_type==1?this.data.loc:atm,
          latitude: 0.0, // 每一个被标点的纬度
          longitude: 0.0, // 每一个被标点的经度
          width: 25, // 使用图标的宽度
          height: 25, // 使用图标的高度
          name: "", // 点击标记点显示的title
          address: "",
          title:"",
          telephone: ""
        };
        // info.id = index;
        let longitude = Number(m.longitude);
        let latitude = Number(m.latitude);
        let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        let x = longitude - 0.0065;
        let y = latitude - 0.006;
        let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi)
        let wz = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        let lon = z * Math.cos(wz);
        let lat = z * Math.sin(wz);
        longitude = lon;
        latitude = lat;
        info.latitude = latitude;
        info.longitude = longitude;
        info.name = m.name;
        info.address = m.address
        info.telephone = m.telephone
        info.title = m.name;
        
        // console.log(info)
        if (m.telephone != null && m.telephone.length > 0){
          targetMarkers.push(info)
          if (m.address.search(areaname) != -1) {
            info.id = id;
            id++;
            tempMarkers.push(info)
          } else if (m.address.search(areaname.slice(0, -1)) != -1) {
              info.id = id;
              id++;
              console.log("修剪后的area为" + areaname.slice(0, -1))
              tempMarkers.push(info)
          }
        }
      })
      console.log(tempMarkers)

      let new_cnt = _this.data.fst_cnt + 1;
      _this.setData({
        fst_cnt:new_cnt
      })
      if(tempMarkers.length===0&&targetMarkers.length!=0&&new_cnt===1){
        let sortTargetList = [];
        targetMarkers.map((item, index) => {
          let distance = funcs.getDistance(mylatitude, mylongitude, item.latitude, item.longitude);
          item.distance = distance;
          sortTargetList.push(item);
        })
        //距离排序（最近优先）
        sortTargetList.sort((item1, item2) => {
          return item1.distance - item2.distance
        })
        console.log(sortTargetList[0].latitude)
        console.log(sortTargetList[0].longitude)
        funcs.getAddressByKey(sortTargetList[0].latitude,
          sortTargetList[0].longitude).then(res=>{
          let new_area = res.data.result.ad_info.district
          _this.reloadDataByCityName(cityname,new_area,switchFlag)
          _this.setData({
            area_name: new_area
          })
          // console.log(res.data.result.ad_info.district)
        })
        return
      }

      let sortList = [];
      tempMarkers.map((item, index) => {
        let distance = funcs.getDistance(mylatitude, mylongitude, item.latitude, item.longitude);
        item.distance = distance;
        sortList.push(item);
      })
      //距离排序（最近优先）
      sortList.sort((item1, item2) => {
        return item1.distance - item2.distance
      })

      _this.setData({
        networkList: sortList
      })

      if (sortList.length !== 0) {
        console.log("sortList.length")
        id = sortList[0].id;
        tempMarkers[id].iconPath = this.data.jigou_type==1?selected_loc:selected_atm;
        tempMarkers[id].width = 32;
        tempMarkers[id].height = 32;
        _this.setData({
          markers: tempMarkers,
          display_flag: true,
          last_selected_id: id,
          selected_name: sortList[0].name,
          selected_address: sortList[0].address,
          selected_latitude: sortList[0].latitude,
          selected_longitude: sortList[0].longitude,
          selected_telephone: sortList[0].telephone,
          selected_distance: sortList[0].distance
        })
        if(switchFlag==true){
          _this.setData({
            latitude: sortList[0].latitude,
            longitude: sortList[0].longitude
          })
        }
      } else {
        _this.setData({
          display_flag: false,
          markers: [],
          latitude: mylatitude,
          longitude: mylongitude
        })
      }
    }).then(res => {
    setTimeout(function () {
      wx.hideLoading()
    }, 1000)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("map监听页面显示")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("map监听页面隐藏")
    // wx.navigateTo({
    //   url: '/pages/list/list',
    // })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("map监听页面卸载")
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  errorNotice:function(res){
    wx.showToast({
        title: "因数据安全考虑\r\n目前暂不开放该功能",
        icon: 'none',
        duration: 2000
      })
  },

  searchNotice:function(res){
    wx.showToast({
      title: "请在主页搜索",
      icon: 'none',
      duration: 2000
    })
  },
  junmToHome: function (res) {
    let data = res.currentTarget.dataset;
    console.log(data)
    var jsonString = JSON.stringify(data);
    //跳转页面并传递json字符串
    wx.navigateTo({
      url: '/pages/home/home?params=' + encodeURIComponent(jsonString)
    })
  },
  call_phone:function (res) {
    let data = res.currentTarget.dataset
    wx.showModal({
      title: "提示",
      content: "拨打 "+data.telephone+" ?",
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: data.telephone,
            success: function () {
              console.log("拨打电话成功！")
            },
            fail: function () {
              console.log("拨打电话失败！")
            }
          })
        }
      }
    })
  }
})